package com.example.onlinemusic.controller;

import com.example.onlinemusic.mapper.MusicMapper;
import com.example.onlinemusic.model.Music;
import com.example.onlinemusic.model.User;
import com.example.onlinemusic.service.MusicService;
import com.example.onlinemusic.tools.Constant;
import com.example.onlinemusic.tools.ResponseBodyMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;


@RestController
@RequestMapping("/music")
public class MusicController {

    @Autowired
    private MusicService musicService;

    @Value("${music.local.path}")
    private String MUSIC_PATH; // 保存音乐的路径
    @Autowired
    private MusicMapper musicMapper;

    /**
     * 上传音乐
     * @param singer
     * @param file
     * @param request
     * @return
     */
    @RequestMapping("/upload")
    public ResponseBodyMessage<Boolean> uploadMusic(@RequestParam String singer,
                                                    @RequestParam("filename") MultipartFile file,
                                                    HttpServletRequest request) {

        HttpSession session = request.getSession(false);
        // 判断是否重复上传
        String filenameAndType = file.getOriginalFilename(); // 音乐的全名包括后缀MP3
        Music music = musicService.selectByTitleAndSinger(filenameAndType.substring(0, filenameAndType.lastIndexOf(".")), singer);
        if (music != null) {
            return new ResponseBodyMessage<>(-1, "重复上传！", false);
        }

        int insert = musicService.insertMusic(singer, file, session);// 调用service
        if (insert > 0) {
            return new ResponseBodyMessage<>(0, "上传音乐成功！", true);
        } else {
            return new ResponseBodyMessage<>(-1, "上传音乐失败，请检查是否为MP3格式！", false);
        }
    }

    /**
     * 播放音乐
     * @param musicName 音乐(带后缀)
     * @return
     */
    @RequestMapping("/get")
    public ResponseEntity<byte[]> getMusic(@RequestParam String musicName){
        try {
            byte[] bytes = Files.readAllBytes(new
                    File(MUSIC_PATH+"/"+musicName).toPath());
            return ResponseEntity.ok(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.badRequest().build();
    }


    /**
     * 删除音乐 （包括本地服务器以及数据库记录）
     * @param musicId
     * @return
     */
    @RequestMapping("/delete")
    public ResponseBodyMessage<Boolean> deleteMusic(@RequestParam int musicId) {
        int deleteResult = musicService.deleteMusicById(musicId);
        if (deleteResult > 0) {
            return new ResponseBodyMessage<>(0, "删除成功！", true);
        } else {
            return new ResponseBodyMessage<>(-1, "删除失败！", false);
        }
    }

    /**
     * 批量删除音乐
     * @param musicIds
     * @return
     */
    @RequestMapping("/deleteSel")
    public ResponseBodyMessage<Boolean> deleteSelMusic(@RequestParam(value = "id[]") List<Integer> musicIds) {
        int result = musicService.deleteSelMusicById(musicIds);
        if (result > 0) {
            return new ResponseBodyMessage<>(0, "批量删除成功！", true);
        } else {
            return new ResponseBodyMessage<>(-1, "批量删除失败！", false);
        }
    }


    /**
     * 查询音乐
     * @param title  不传参数表示查询所有音乐
     * @return
     */
    @RequestMapping("/findMusic")
    public ResponseBodyMessage<List<Music>> findMusicByName(@RequestParam(required = false) String title) {
        List<Music> musics = null;
        if (title == null) {
            musics = musicService.findAllMusic();
        } else {
            musics = musicService.findMusicByName(title);
        }

        return new ResponseBodyMessage<>(0, "查询所有音乐成功！", musics);
    }


    /**
     * 展示全部的音乐到数据库
     * @return
     */
    @RequestMapping("/getAllMusic")
    public ResponseBodyMessage<List<Music>> getAllMusic() {
        List<Music> musics = musicService.findAllMusic();
        return new ResponseBodyMessage<>(0, "展示全部音乐成功！", musics);
    }

}
